package com.uni.controllers;

import java.io.Serializable;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.*;

import com.uni.db.GenericService;
import com.uni.domain.*;
import com.uni.utils.CollectionUtil;

@Controller
@RequestMapping("/markJournal.htm")
@SessionAttributes(types = Course.class)
public class MarkJournalController {

    @Autowired
	@Qualifier("groupService")
	private GenericService<Group> groupService;
    
    @Autowired
	@Qualifier("userService")
	private GenericService<User> userService;
    
    @RequestMapping(method = RequestMethod.GET)
	public String viewData(@RequestParam(value="id", required=false) Long id, ModelMap model) {
    	String erMsg = "there is something with logic in application. You are student, or prepod?";
    	
    	if(isPrepodView()){ //TODO or admin, or.. Spring Security probably ll help with it.
    		if(id != null & id > 0){
        		Group group = groupService.get(id);
    			model.addAttribute("courses", new MarkJournal(group));
    			return "markJournalForPrepod";
        	} else {
        		erMsg = "id must be specified";
        	}
    	}
    	
    	if(isStudentView()){
    		User student = userService.get(studentId());
    		if(student.isStudent()){
    			model.addAttribute("courses", student.getGroup().getCourses());
				try {
					model.addAttribute("results", CollectionUtil.buildMap(student.getResults(), "lection"));
				} catch (Exception e) {
					erMsg = "here something wrong with build map from set";
					e.printStackTrace();
				}
				return "markJournalForStudent";
    		} else {
    			erMsg = "there is something with logic in application. You are student, or not?";
    		}
    	}
    	
		model.addAttribute("title", "error");
		model.addAttribute("message", erMsg);
    	return "error";
	}

	private boolean isStudentView() {
		return true;
	}

	private boolean isPrepodView() {
		return !isStudentView();
	}

	private Long studentId() {
		return 0L;
	}
}
